/**
 * Source inspired from the WordWidget example in the Android Sample Apps
 */
package in.animeshpathak.android.nexttransit;


import in.animeshpathak.android.nexttransit.R;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * A widget that shows the train time for the next two trains matching the constraints 
 * set in the settings page
 * @author pathak
 *
 */
public class TrainTimeWidget extends AppWidgetProvider{

	public static final String LOG_TAG = "NEXT_DEP";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		// perform the update in a service
		Log.d(LOG_TAG, "Update called. Starting Service");
		context.startService(new Intent(context, TrainUpdateService.class));
	}

	public static class TrainUpdateService extends Service{

		static int count = 0;
		final Handler mHandler = new Handler();

		@Override
		public void onStart(Intent intent, int startId) {

//			Toast.makeText(getApplicationContext(), R.string.query_start_message, Toast.LENGTH_SHORT).show();
			new Thread(){

				Context context = getApplicationContext();

				public void run(){
					
					//TODO Pick from preferences
					String train_code = "MONA";
					//get latest train time
					String url = "http://transilien.mobi/TempReelSaisieSubmit.do?etapeDepart=0&etapeArrivee=0&debutDepart=Chemin+d'Antony&debutArrivee=facultatif&trouver.x=37&trouver.y=13&trouver=Trouver";
					
					RemoteViews updateViews;

					ComponentName thisWidget = new ComponentName(this.context, TrainTimeWidget.class);
					AppWidgetManager manager = AppWidgetManager.getInstance(this.context);

					
					//Set widget as loading...
					updateViews = new RemoteViews(context.getPackageName(), R.layout.nexttrain_loading);
					updateViews.setTextViewText(R.id.train_name, train_code);
					updateViews.setTextViewText(R.id.train_time, getString(R.string.loading));
					manager.updateAppWidget(thisWidget, updateViews);
					
					
					
					// Build the widget update for today
					String time = getString(R.string.error);
					updateViews = new RemoteViews(context.getPackageName(), R.layout.nexttrain);

					//update Train name view
					updateViews.setTextViewText(R.id.train_name, train_code);

					//set button to refresh

					Intent newIntent = new Intent(getApplicationContext(), TrainUpdateService.class);
					PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, newIntent, PendingIntent.FLAG_ONE_SHOT);
					updateViews.setOnClickPendingIntent(R.id.train_name, pendingIntent);
					updateViews.setOnClickPendingIntent(R.id.train_time, pendingIntent);
					//updateViews.setOnClickPendingIntent(R.id.widget_refresh_button, pendingIntent);


					// Push update for this widget to the home screen

					try {
						Document doc = Jsoup.connect(url).get();
						//set it on the widget

						for(Element row: doc.select("table#listeTrain > tr")){
							Elements columns = row.getElementsByAttributeValue("id", "Train");
							if (columns.size() == 0)
								continue;
							//if second td within row has MONA
							if (columns.first().text().equalsIgnoreCase("MONA")){
								//store third td as time, break
								time = row.getElementsByAttributeValue("id", "heure").first().text();
								break;
							}
						}

						//update Train time view
						//updateViews.setTextViewText(R.id.train_time, "01:00");
						Log.d(LOG_TAG, "Setting time as " + time);
						//            updateViews.setTextViewText(R.id.train_time, String.valueOf(count++));
//						mHandler.post(new Runnable(){
//							public void run(){
//								Toast.makeText(getApplicationContext(), R.string.query_success_message, Toast.LENGTH_SHORT).show();
//							}
//						});

					} catch (IOException e) {
//						mHandler.post(new Runnable(){
//							public void run(){
//								Toast.makeText(getApplicationContext(), R.string.query_failure_message, Toast.LENGTH_SHORT).show();
//							}
//						});
						Log.e(LOG_TAG, "Error accessing url", e);
					}
					updateViews.setTextViewText(R.id.train_time, time);
					manager.updateAppWidget(thisWidget, updateViews);


				}


			}.start();
		}


		@Override
		public IBinder onBind(Intent arg0) {
			// TODO Auto-generated method stub
			return null;
		}



	}

}
